<?php

use Core\API_Controller;

use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\ExecutePayment;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use Models\User;
use Models\Config;
use Models\Recharge;

class RechargeController extends API_Controller
{
	public function index($id)
	{
		$recharge = (new Recharge)->findOrFail($id);

		$apiContext = new \PayPal\Rest\ApiContext(
        	new \PayPal\Auth\OAuthTokenCredential(
	            'Acob13Jk1eLhSXpbgwtVWErhkGQMXig4mztU6G8O4wKJfrb3Ktai6NNrSXO8pOAQ_pUewUDXNgDb3mYS',     // ClientID
	            'EMSVsYIZ-uN3P3uMAPQOrmKcpaMJMZu6qj4BKxrUruLfKAeDlMrzGxdlihNBsh3OQg58_Hm5VdU9wMSr'      // ClientSecret
		    )
		);

		$apiContext->setConfig(array(
			'http.CURLOPT_SSLVERSION' => CURL_SSLVERSION_TLSv1,
			'mode' => 'live'
		));

		// item
		$payer = new Payer();
		$payer->setPaymentMethod("paypal");

		$total = round($recharge['recharge'], 2);
		$amount = new Amount();
		$amount->setCurrency("GBP")
		    ->setTotal($total);

		// 事务
		$baseUrl = WWW_URL.'/frontend';
		$redirectUrls = new RedirectUrls();
		$redirectUrls->setReturnUrl(WWW_URL."/api/recharge/paypalAgree/".$recharge['id'])
		    ->setCancelUrl("$baseUrl/#/me/balance");
		$transaction = new Transaction();
		$transaction->setAmount($amount)
		    // ->setItemList($itemList)
		    ->setDescription("Payment description")
		    ->setInvoiceNumber(uniqid());

		$payment = new Payment();
		$payment->setIntent("sale")
		    ->setPayer($payer)
		    ->setRedirectUrls($redirectUrls)
		    ->setTransactions(array($transaction));

		$request = clone $payment;

		try {
		    $payment->create($apiContext);
		} catch (Exception $ex) {
			log_message('error', "paypal申请支付链接出错".json_encode($request).', exception:'.$ex);
			echo '<pre>';
			print_r($ex);
			echo '</pre>';
    		return $this->error('吊起支付失败');
		}

		$approvalUrl = $payment->getApprovalLink();
		redirect($approvalUrl);
	}

	public function paypalAgree($id)
	{
		$recharge = (new Recharge)->findOrFail($id);

		$apiContext = new \PayPal\Rest\ApiContext(
        	new \PayPal\Auth\OAuthTokenCredential(
	            'Acob13Jk1eLhSXpbgwtVWErhkGQMXig4mztU6G8O4wKJfrb3Ktai6NNrSXO8pOAQ_pUewUDXNgDb3mYS',     // ClientID
	            'EMSVsYIZ-uN3P3uMAPQOrmKcpaMJMZu6qj4BKxrUruLfKAeDlMrzGxdlihNBsh3OQg58_Hm5VdU9wMSr'      // ClientSecret
		    )
		);

		$apiContext->setConfig(array(
			'http.CURLOPT_SSLVERSION' => CURL_SSLVERSION_TLSv1,
			'mode' => 'live'
		));

		// 执行支付过程
		$paymentId = $_GET['paymentId'];
    	$payment = Payment::get($paymentId, $apiContext);

    	$execution = new PaymentExecution();
    	$execution->setPayerId($_GET['PayerID']);

    	$transaction = new Transaction();
	    $amount = new Amount();

        $amount->setCurrency('GBP');
	    $amount->setTotal(round($recharge['recharge'], 2));
	    $transaction->setAmount($amount);

	    $execution->addTransaction($transaction);

	    try {
	        $result = $payment->execute($execution, $apiContext);

	        try {
	            $payment = Payment::get($paymentId, $apiContext);
	        } catch (Exception $ex) {
	        	log_message('error', "Payment::get() error, paymentId:{$paymentId}, exception:".$ex);
	        	echo '支付失败';
	            exit(1);
	        }
	    } catch (Exception $ex) {
	    	log_message('error', "Payment::execute error, execution:".json_encode($execution).", apiContext:".json_encode($apiContext).", ex:".$ex);
	    	echo '支付失败';
	        exit(1);
	    }


		$add = Recharge::getPresent($recharge['money']);

	    $this->db->trans_start();
		$user = (new User)->find($recharge['user_id']);
	    $this->db
			->where('id', $recharge['user_id'])->set('balance', 'balance+'.($recharge['money']), false)
			->update('users');
	    $this->db->where('id', $recharge['id'])->set('status', 2)->update('recharges');
		// 保存资金记录
		$recharge->saveMoneylog([
			'last' => $user['balance'],
			'now' => $user['balance']+$recharge['money'],
			'desc' => "微商城充值 {$recharge['recharge']} 送 {$recharge['present']}",
			'pay_type' => 4,
			'from' => 'frontend',
		]);
	    $this->db->trans_complete();

	    redirect(WWW_URL.'/frontend/#/me/balance');
	}
}
